const subBtn = document.querySelector("input[type='submit']");
const form = document.querySelector("form");
const input = document.querySelector("input[type='checkbox']");
const userEl = document.querySelector("input[type='text']");
const pwdEl = document.querySelector("input[type='password']");
const messages = document.querySelectorAll("span.message");
const userReg = /^[a-zA-Z0-9_-]{4,16}$/;
const pwdReg = /^\w\d{4,8}$/;
const userInfo = [];
let isHad = false;
userEl.addEventListener("keydown",function(){
    if(userReg.test(this.value)){
        messages[0].style.color = "green";
    }
    else{
        messages[0].style.color = "red";
    }
    messages[0].innerHTML = userReg.test(this.value)? "格式正确" : "用户名以字母数字下划线或减号开头，长度不超过16位"
},false)

pwdEl.addEventListener("keydown",function(){
    if(pwdReg.test(this.value)){
        messages[1].style.color = "green";
    }
    else{
        messages[1].style.color = "red";
    }
    messages[1].innerHTML = pwdReg.test(this.value)?"格式正确" : "密码只以一位字母开头，后续都为数字,其数字至少为4位，且长度不超过9位"
},false)

form.addEventListener("submit",function(e){
    e.preventDefault();
    let userName = userEl.value;
    let passWord = pwdEl.value;
    const user = {userName,passWord};
    if(!userReg.test(userName) || !pwdReg.test(passWord)){
        alert("用户名或密码格式不正确，注册失败");
    }
    else if(!input.checked){
        alert("请勾选用户协议");
    }
    else{
        if(!isHad){
            isHad = true;
            userInfo.push(user);
            localStorage.setItem('userinfo',JSON.stringify(userInfo));
        }
        else{
            userInfo.forEach((item)=>{
                if(item.userName === userName){
                    alert("用户名已存在请重新输入")
                }
                else{
                    userInfo.push(user);
                    localStorage.setItem('userinfo',JSON.stringify(userInfo));
                }
            })
        }
        
        location.href="http://localhost:8888/html/login.html";
    }
})